<template>
  <div id="star_map01">
    <p class="data_time">
      <span>数据更新时间：</span>
      <span style="color:#888">{{ timestamp(time, "Y-M-D h:m") }}</span>
    </p>
    <radio_group
      :radio_values="[
        '达人指数榜',
        '涨粉指数榜',
        '星图指数榜',
        '种草指数榜',
        '精选指数榜',
        '传播指数榜'
      ]"
      v-model="my_radio01"
      title="榜单"
      isSearch="1"
      :class="{ titadd: 2 > 1 }"
    />
    <category_industry v-model="industryItemObj" :class="'mt_10'"/>
    <section>
      <div class="btn_group">
        <button @click="generatorImage">
          <span></span>分享
        </button>
        <button @click="export_data">
          <span></span>导出
        </button>
      </div>
      <ul
        class="fixedThead"
        ref="fixedThead"
        :class="{ isShow: isFixed }"
        :style="showLeft == true ? 'left:222px' : 'left:98px'"
      >
        <li tc>排名</li>
        <li>达人</li>
        <li tc>粉丝总数</li>
        <li tc>
          {{
          my_radio01.slice(0, -1) == "达人指数"
          ? "星图指数"
          : my_radio01.slice(0, -1)
          }}
        </li>
        <li tc>操作</li>
      </ul>
      <table class="table" ref="capture01">
        <thead>
          <tr>
            <th>排名</th>
            <th>达人</th>
            <th>粉丝总数</th>
            <th>
              {{
              my_radio01.slice(0, -1) == "达人指数"
              ? "星图指数"
              : my_radio01.slice(0, -1)
              }}
            </th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in table_data" :key="'table' + index" :id="!index ? 'tr1' : ''">
            <td class="td td_01">
              <div>
                <span>{{ item.rank }}</span>
              </div>
            </td>
            <td class="td td_02">
              <div>
                <img
                  :src="item.logo"
                  class="pointer"
                  @click="go_to_page01(item.authorId)"
                  v-errorImg:talent
                />
                <span class="dot pointer" @click="go_to_page01(item.authorId)">{{ item.nickName }}</span>
              </div>
            </td>
            <td class="td td_03">
              <div>{{ format_num(item.totalFans) }}</div>
            </td>
            <td class="td td_04">
              <div>{{ format_num(item.hint) }}</div>
            </td>
            <td class="td td_05">
              <div>
                <button @click="go_to_page01(item.authorId)">查看详情</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="upgradeBox" v-if="!permissions">
        <RankUpgrade class="rankUpgrade" />
      </div>
      <!-- <p
        class="nothing"
        v-show="
          table_data.length < 30 &&
            !loading &&
            permissions &&
            table_data.length != 0
        "
      >我是有底线的～</p> -->
      <div class="pageBox" v-if="!loading">
        <el-pagination
          v-if="!loading"
          background
          layout="prev, pager, next, jumper"
          :total="count"
          :page-size="30"
          :current-page="page"
          @current-change="get_data"
          :hide-on-single-page="true"
        ></el-pagination>
      </div>

      <div
        v-loading="loading"
        v-if="loading"
        class="loading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
      ></div>
    </section>
    <div class="empty" v-show="!loading && table_data.length == 0 && permissions">
      <img src="@/assets/liu/zw.png" />
      <p>暂无数据</p>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas';
import category_industry from '@/component/category_industry';
export default {
  data() {
    return {
      loading: true,
      // 短视频达人榜
      cancel: null,
      page: 1,
      count: 0,

      my_radio01: '达人指数榜',
      //   直播达人榜
      permissions: 1,
      table_data: [],
      time: '',
      showLeft: true,
      isFixed: false,
      offsetTop: 0,
      industryItemObj:{
        name:'全部',
        id:'0'
      }
    };
  },
  components:{
    category_industry
  },
  computed: {
    listen_change() {
      const { my_radio01, industryItemObj } = this;
      return { my_radio01, industryItemObj };
    }
  },
  created: function () {
    this.get_data();
    this.$watch(
      'listen_change',
      this.debounce((newValue, oldValue) => {
        this.page = 1;
        this.table_data = [];
        this.get_data();
      }, 0)
    );
  },
  watch: {
    '$store.state.left_nav_flag'(old, newOld) {
      this.showLeft = newOld;
      if ((newOld = false)) {
        this.setTBBar();
      } else {
        this.setTBBar();
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.initHeight);
    window.addEventListener('resize', () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar();
    });
  },
  methods: {
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false;
      let nodes = pNode.childNodes;
      let newList = [];
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node);
        }
      }
      return newList;
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl;
        let ulEl = this.$refs.fixedThead;
        let tr1 = document.querySelector('#tr1');
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1);
          let liEls = this.getChilds(ulEl);

          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + 'px';
          }
        }
      });
    },
    get_data(cpage) {
      this.loading = true;
      this.table_data = [];
      let that = this;
      if (cpage) {
        that.page = cpage;
        that.backTop();
        //console.log("page", this.page);
      }
      let HintType;
      this.permissions = 1;
      switch (this.my_radio01) {
        case '达人指数榜':
          HintType = 0;
          break;
        case '涨粉指数榜':
          HintType = 1;
          break;
        case '星图指数榜':
          HintType = 2;
          break;
        case '种草指数榜':
          HintType = 3;
          break;
        case '精选指数榜':
          HintType = 4;
          break;
        case '传播指数榜':
          HintType = 5;
          break;
      }
      this.$axios
        .post(
          '/api/author/GetStarMapMasters',
          {
            Category: this.industryItemObj.id,
            HintType: HintType,
            Index: that.page,
            Size: 30
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel) that.cancel();
              that.cancel = c;
            })
          }
        )
        .then(response => {
          this.loading = false;
          if (response.data.code == 0) {
            this.table_data = response.data.data.masters;

            this.time = response.data.data.timeSpan;
            response.data.data.masters.length < 10 ? (this.busy = true) : (this.busy = false);

            that.count = response.data.data.totalCount;
          }
          if (response.data.code == 1003) {
            this.permissions = 0;
            this.table_data01 = [];
          } else {
            this.permissions = 1;
          }
          this.setTBBar();
        })
        .catch(error => {
          console.log(error);
        });
    },
    generatorImage() {
      var that = this;
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        customClass: 'customClass'
      });
      var shareContent;
      shareContent = this.$refs.capture01; //需要截图的包裹的（原生的）DOM 对象
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement('canvas'); //创建一个canvas节点
      //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
      var scale = 1;
      canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale * scale; //定义canvas高度 *缩放
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';
      canvas.getContext('2d').scale(scale, scale); //获取context,设置scale
      var opts = {
        dpi: window.devicePixelRatio,
        scale: scale, // 添加的scale 参数
        useCORS: true,
        canvas: canvas, //自定义 canvas
        logging: true //日志开关
      };
      html2canvas(shareContent, opts).then(canvas => {
        let str;

        str = `《短视频达人榜-${this.timestamp(new Date().getTime() / 1000, 'Y年M月D日')}》.png`;

        canvas.toBlob(
          function (blob) {
            const eleLink = document.createElement('a');
            eleLink.download = str;
            eleLink.style.display = 'none';
            // 字符内容转变成blob地址
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
          },
          'image/png',
          1
        );
        loading.close();
      });
    },
    export_data() {
      let that = this;
      let str;

      str = `排名,达人,粉丝总数,${
        that.my_radio01.slice(0, -1) == '达人指数' ? '星图指数' : that.my_radio01.slice(0, -1)
      }\n`;
      for (let i = 0; i < that.table_data.length; i++) {
        str += `${that.table_data[i].rank},\"${that.table_data[i].nickName.replace(
          /"/g,
          '""'
        )}\",${that.format_num(that.table_data[i].totalFans)},${that.format_num(
          that.table_data[i].hint
        )}\n`;
      }
      var blob = new Blob([str], { type: 'text/plain;charset=utf-8' }); //解决中文乱码问题
      blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
      let object_url = window.URL.createObjectURL(blob);
      var link = document.createElement('a');
      link.href = object_url;
      let str_name;

      str_name = `《短视频达人榜-${this.timestamp(new Date().getTime() / 1000, 'Y年M月D日')}》.csv`;

      link.download = str_name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    loadMore: function () {
      this.get_data();
    },
    go_to_page01(id) {
      let router = this.$router.resolve({
        path: `/talent_main/tdetails/${id}/${0}`
      });
      window.open(router.href, '_blank');
    },
    backTop() {
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.isFixed = scrollTop > 300 ? true : false;
    }
  }
};
</script>
<style scoped lang="less">
#star_map01 {
  min-height: 100vh;
  padding-bottom: 1px;
}
.table {
  thead {
    tr {
      th:nth-child(2) {
        text-align: left;
        padding-left: 10px;
      }
    }
  }
  tbody {
    tr {
      height: 78px;
    }
  }
  .td_05 {
    width: 12%;
    button {
      width: 88px;
      height: 32px;
      background-color: transparent;
      border: 1px solid #fd7f2c;
      border-radius: 4px;
      font-size: 14px;
      font-weight: normal;
      font-stretch: normal;
      line-height: 30px;
      letter-spacing: 0px;
      color: #fd7f2c;
      text-align: center;
    }
    button:hover {
      border-color: #ff924b;
      color: #ff924b;
    }
  }
  .td_03,
  .td_04 {
    width: 12%;
    font-size: 15px;
    font-family: DINAlternate-Bold;
  }
  .td_02 {
    width: 50%;
    img {
      border-radius: 50%;
      width: 50px;
      height: 50px;
      margin-right: 12px;
      border: 1px solid #e5e5e5;
    }
    span {
      width: 200px;
      font-size: 14px;
      color: #222;
      font-weight: 600;
      display: inline-block;
    }
    span:hover {
      color: #ff924b;
    }
    > div {
      height: 70px;
      display: flex;
      align-items: center;
      justify-content: flex-start !important;
    }
  }
  .td_01 {
    width: 10%;
    font-size: 15px;
    font-family: DINAlternate-Bold;
    img {
      width: 30px;
      height: 32px;
    }
  }
  .td {
    > div {
      height: 70px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.btn_group {
  margin-bottom: 14px;
  text-align: right;
  button {
    width: 70px;
    height: 32px;
    border-radius: 4px;
    border: solid 1px #e5e5e5;
    font-size: 14px;
    // line-height: 30px;
    box-sizing: border-box;
    color: #555;
    text-align: center;
  }
  button:nth-of-type(2) {
    color: #67ac5b;
    border: 1px solid #67ac5b;
  }

  > button:nth-child(1) {
    margin-right: 10px;
    span {
      display: inline-block;
      width: 14px;
      height: 14px;
      background: url('../../../assets/zhao/fenx.png') no-repeat;
      background-size: 100% 100%;
      margin-right: 4px;
      position: relative;
      top: 2px;
    }
  }
  > button:nth-child(2) {
    span {
      display: inline-block;
      width: 14px;
      height: 14px;
      background: url('../../../assets/zhao/daoc.png') no-repeat;
      background-size: 100% 100%;
      margin-right: 4px;
      position: relative;
      top: 2px;
    }
  }
  button:nth-of-type(1):hover {
    color: #777;
    span {
      background: url('../../../assets/zhao/fenx_h.png') no-repeat;
      background-size: 100% 100%;
    }
  }
  button:nth-of-type(2):hover {
    color: #80be76;
    border-color: #80be76;
    span {
      background: url('../../../assets/zhao/daoc_h.png') no-repeat;
      background-size: 100% 100%;
    }
  }
}
#star_map {
  background: #fff;
  height: fit-content;
  margin-left: 20px;
  margin-right: 20px;
  padding: 0 20px;
  margin-top: 20px;
  padding-top: 10px;
  min-height: 100vh;
  // 升级会员
  .upgradeBox {
    min-height: 60vh;
    position: relative;
    .rankUpgrade {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .data_time {
    margin-top: -52px;
    margin-bottom: 32px;
    margin-right: 0;
    text-align: right;
    > span:first-child {
      font-size: 14px;
      color: #888888;
      // margin-right: 9px;
      letter-spacing: 0;
    }
    > span:last-child {
      font-size: 15px;
      // font-family: DINAlternate-Bold;
      color: #1779ff;
      letter-spacing: 0;
    }
  }
  .fixedThead {
    display: none;
    position: fixed;
    top: 60px;
    left: 200px;

    border-radius: 4px;
    font-size: 14px;
    font-weight: 600;
    color: #555;
    background-color: #f5f9ff;
    height: 48px;
    line-height: 48px;
    overflow: hidden;
    z-index: 99;
    font-size: 0;
    li {
      box-sizing: border-box;
      display: inline-block;
      font-size: 14px;
    }

    &.isShow {
      display: block;
    }
  }
  [tc] {
    text-align: center;
  }
  [tl] {
    text-align: left;
  }
  [tr] {
    text-align: right;
  }
}
</style>
